package com.foreknow.filter;

import javax.servlet.*;
import java.io.IOException;

/**
 * 转换字符编码的过滤器(filter)
 */
public class CharactorEncodingFilter implements Filter {
    private FilterConfig filterConfig;
    private String encoding = "ISO8859-1";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        encoding = filterConfig.getInitParameter("encode"); //utf-8
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding(encoding);
        servletResponse.setContentType("text/html;charset=utf-8");
        //如果还有下一个过滤器,就要将这个请求交给下一个过滤器,如果没有,就将请求交给Servlet来处理
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        filterConfig = null;
    }
}
